import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '@/views/Films'
import Filmscinemas from '@/views/FilmsCinemas'
import Nowplaying from '@/views/films/Nowplaying'
import Comingsoon from '@/views/films/Comingsoon'
import Cinemas from '@/views/Cinemas'
import Cinemasticket from '@/views/CinemasTicket'
import City from '@/views/City'
import Search from '@/views/cinemas/Search'
import Inform from '@/views/Inform'
import Login from '@/views/Login'
// import Center from '@/views/Center'   // 使用路由懒加载
import Details from '@/views/Details'
// import Order from '@/views/Order'   // 使用路由懒加载

// 引进vuex
import vuex from '@/store/index';

Vue.use(VueRouter)  // 注册路由插件，两个全局 router-view 和 router-link

// 路由配置表
const routes = [
  {
    path: '/films',
    component: Films,
    // 嵌套路由
    children: [
      {
        path: '/films/nowplaying',
        component: Nowplaying,
      },
      {
        path: '/films/comingsoon',
        component: Comingsoon,
      },
      {
        path: '/films',
        redirect: '/films/nowplaying'
      }
    ]
  },
  {
    name: 'hhlDetails',   // 命名路由， 也可以拿到
    path: '/details/:id',   // 动态二级路由
    component: Details
  },
  {
    path: '/cinemas',
    component: Cinemas
  },
  {
    path: '/filmscinemas/:filmId',
    component: Filmscinemas
  },
  {
    path: '/city',
    component: City
  },
  {
    path: '/cinemas/search',
    component: Search
  },
  {
    name: 'cinemasticket',
    path: '/cinemasticket/:filmId/:cinemaId/:date',
    component: Cinemasticket
  },

  {
    path: '/inform',
    component: Inform
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/center',
    // 路由懒加载
    component: ()=>import('@/views/Center'),
    meta: {
      needLogin: true    // 判断是否登录
    },
    // 局部路由拦截（路由独享守卫）
    // beforeEnter: (to, from, next) => {
    //   // ...
    // }
  },
  {
    path: '/order',
    // 路由懒加载
    component: ()=>import('@/views/Order'),
    meta: {
      needLogin: true    // 判断是否登录
    }
  },
  // 重定向：以上路径都没找到时，就来到这里
  {
    path: '*',
    redirect: '/films'
  },
]

const router = new VueRouter({
  mode: 'history',   // 路由模式，  vue-router 默认 hash 模式 ，如果不想要很丑的 hash，我们可以用路由的 history 模式
  routes
})

// 路由全局拦截（守卫）
router.beforeEach((to, from, next) => {
  // console.log(to)

  // 如果是从电影影院购票界面跳过来，则first=0，下次再进入时显示的就是需要查看的电影信息
  if (from.name ==='cinemasticket'){
    vuex.commit('changeFirst',0)
    // console.log(vuex.state.first)
    next()
  }
  // console.log(vuex.state.first)
  // if(某几个需要授权的路由){
  //   if(授权通过){
  //     next()
  //   }else {
  //     next(/login)
  //   }
  // }else {
  //   next()
  // }

  if (to.meta.needLogin) {
    if (localStorage.getItem('token')) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }   // query 保存是从哪个页面过去的(想要去到的页面)
      })
    }
  } else {
    next()
  }
})

export default router
